# -*- coding: utf-8 -*-
import requests
import json
import hashlib
import base64
import hmac
import time

"""
通过飞书机器人的webhook发送消息
"""


class IFLYTEK_ROBOT:
    def __init__(self, secret: str = '', webhook: str = ''):
        self.secret = secret  # webhook机器人的签名
        self.webhook = webhook  # webhook机器人链接
        self.headers = {
            'Content-Type': 'application/json',
        }

    def gen_sign(self, timestamp, secret):
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
        sign = base64.b64encode(hmac_code).decode('utf-8')
        return sign

    def send_msg(self, msg_type='text', msg=''):
        post_data = {
            "msg_type": msg_type,
            "content": {
                "text": msg
            }
        }
        if self.secret:  # 不为空则表示开启签名校验
            timestamp = int(time.time())
            sign = self.gen_sign(timestamp, self.secret)
            post_data['timestamp'] = str(timestamp)
            post_data['sign'] = sign

        r = requests.post(self.webhook, headers=self.headers, data=json.dumps(post_data), timeout=30)
        try:
            # {'code': 0, 'msg': 'success', 'data': {}}
            res = json.loads(r.text)
        except:
            error = 'json解析失败:{}'.format(r.text)
            res = {'code': -1, 'msg': error}
        return res

